import { Injectable } from '@angular/core';
import { Http, RequestOptions, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { NzMessageService } from 'ng-zorro-antd';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()

export class UserService {

  constructor(private http: Http,
              private _message: NzMessageService) { }

  login(payload: object): Observable<any> {
    return this.http.post(`api/user/auth`, payload)
    .map(this.parseData)
    .catch(this.handleError);
  }

  register(payload): Observable<any> {
    return this.http.post(`api/user/register`, payload)
      .map(this.parseData)
      .catch(this.handleError);
  }

  private parseData(res: Response) {
    return res.json() || [];
  }

  private handleError(error: Response | any) {
    // This returns another Observable for the observer to subscribe to
    if (error._body) {
      const err = error.json();
      return Observable.throw(err);
    }
    const msg = error.message ? error.message : error.toString();
    return Observable.throw({msg});
  }
}
